package io.bio;

import org.junit.Test;

import java.io.*;

public class ReadFile {

    private String filePath = "D:\\info.txt";

    @Test
    public void readFileAndPrint(){
        try {
            InputStream is = new FileInputStream(filePath);
            byte[] cach = new byte[is.available()];
            is.read(cach);
            String str = new String(cach);
            System.out.println(str);
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void readFileAndWritMore(){
        try {
            OutputStream os = new FileOutputStream(filePath, true);
            os.write("\n末尾追加字符".getBytes("utf-8"));
            os.flush();
            os.close();
        } catch (IOException e){
            e.printStackTrace();
        }
    }

    @Test
    public void readFileAndAppendMore(){
        try {
            Writer writer = new FileWriter(filePath, true);
            writer.append("\n末尾追加字符2");
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void readAndPrint(){
        try {
            Reader reader = new FileReader(filePath);
            BufferedReader br = new BufferedReader(reader);
            StringBuilder strBu = new StringBuilder();
            String str;
            while ((str = br.readLine())!=null){
                strBu.append(str).append("\n");
            }
            br.close();
            reader.close();
            System.out.println(strBu.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
